var util = require('../util'),
  nodemailer = require('nodemailer'),
  weixinuserDao = require('../db').weixinuser,
  log = require('../util').log,
  config = require('../util').config,
  Promise = require('bluebird'),
  https = require('https');

/**
 * 输入edu邮箱完成注册
 * @param message xml数据
 * @returns Promise
 */
function register(message) {

  // 匹配以edu结尾或者以edu.xx结尾的email
  if (message.Content &&
    message.Content.match(/^[A-Za-zd]+([-_.][A-Za-zd]+)*@([A-Za-zd]+[-.])+(edu|edu.[a-z]{2})$/) || false) {

    return Promise.all([weixinuserDao.findOneByCertificatedEmail(message.Content),
      weixinuserDao.findByOpenId(message.FromUserName)]).then(function (data) {
      var dataByEmail = data[0];
      var dataByOpenid = data[1];

      // 用户已经注册过(email不为空 certificated为true)
      if (dataByOpenid && dataByOpenid.email && dataByOpenid.certificated) {
        return Promise.resolve({
          action_type: 'register',
          msg: util.weixin.getTextMsg(message.ToUserName, message.FromUserName, '您已经是注册用户了！')
        });
      } else {

        // email还没有被注册
        if (!dataByEmail) {
          dataByOpenid.email = message.Content;

          return weixinuserDao.findOneAndUpdate({openid: dataByOpenid.openid}, dataByOpenid).then(function () {
            var referenceCode = dataByOpenid.reference_code;
            util.sandbox.emit(util.sandbox.MSG.AWARD_REGISTER_QRCODE, {
              trigger: dataByOpenid,
              referenceCode: referenceCode,
              actionType: 'register'
            });
            util.sandbox.emit(util.sandbox.MSG.MAIL_VERIFICATION, {
              'to': message.Content,
              'openid': message.FromUserName
            });
            return {
              action_type: 'register',
              msg: util.weixin.getTextMsg(message.ToUserName, message.FromUserName, '恭喜你注册为科研共济会免费会员')
            }
          });
        } else {

          // 邮箱已注册过
          return Promise.resolve({
            action_type: 'register',
            msg: util.weixin.getTextMsg(message.ToUserName, message.FromUserName, '您输入的邮箱已经被注册，请使用其他邮箱完成注册')
          });
        }
      }
    }).catch(util.log.log2Error);
  } else {

    // 邮箱格式错误
    return Promise.resolve({
      action_type: 'register',
      msg: util.weixin.getTextMsg(message.ToUserName, message.FromUserName, '请输入正确的edu邮箱')
    });
  }
}

function unregister(message) {
  return new Promise(function (resolve, reject) {
    return weixinuserDao.findByOpenId(message.FromUserName).then(function (data) {
      var dataByOpenid = data;
      if(dataByOpenid){
        dataByOpenid.certificated = false;
        dataByOpenid.subscribe = 0;

        return weixinuserDao.findOneAndUpdate({openid: dataByOpenid.openid}, dataByOpenid).then(function (result) {
          return resolve(result);
        },function(err){
          if(err){
            util.log.log2Error(err);
            return reject(err);
          }
        });
      }else{
        util.log.log2Error('openID为:'+message.FromUserName+"的用户不存在！");
        return resolve('openID为:'+message.FromUserName+"的用户不存在！");
      }
    });
  });
}

module.exports = {
  register: register,
  unregister: unregister
};